//
//  SendAudioView.m
//  自定义聊天界面和键盘-多选照片-语音-表情-文本
//
//  Created by qinlongqing on 14-10-14.
//  Copyright (c) 2014年 qinlongqing. All rights reserved.
//

#import "SendAudioView.h"
#import "QinKeyBoardController.h"
@implementation SendAudioView
{
    CGPoint point_begain;
    
    BOOL isRecoreding;
    BOOL isCancel;
    UIButton *recordingButton;
    //录音动画计时器
    NSTimer *timer;
    NSInteger timeCount;
}
- (instancetype)init{
    self = [super init];
    if (self) {
        [self setup];
    }
    return self;
}

- (instancetype)initWithFrame:(CGRect)frame{
    self = [super initWithFrame:frame];
    if (self) {
        [self setup];
    }
    return self;
}

- (void)setup{
    recordingButton = [[UIButton alloc]initWithFrame:CGRectMake((self.frame.size.width - 98)/2, (kSendAudioViewFrameHeight-98)/2, 98, 98)];
//    [recordingButton setTitle:@"开始录音" forState:UIControlStateNormal];
//    [recordingButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
//    [recordingButton setBackgroundColor:[ClassMethodsViewController colorWithHexString:@"#4fc1e9"]];
//    recordingButton.layer.cornerRadius = 40;
//    recordingButton.layer.borderWidth = 0.5;
    
    [recordingButton setImage:[UIImage imageNamed:@"聊天_未选中语音.png"] forState:UIControlStateNormal];
    [recordingButton setImage:[UIImage imageNamed:@"聊天_选中语音.png"] forState:UIControlStateHighlighted];

    recordingButton.layer.borderColor = [UIColor lightGrayColor].CGColor;
    UITapGestureRecognizer *tapGes=[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(dotapGes:)];
    [recordingButton addGestureRecognizer:tapGes];
    
    UILongPressGestureRecognizer *longPress=[[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(doLongPress:)];
    longPress.delegate=self;
    longPress.minimumPressDuration=0.5;
    [recordingButton addGestureRecognizer:longPress];
    
    
    [recordingButton addTarget:self action:@selector(doupVoice:) forControlEvents:UIControlEventTouchUpInside];
    [recordingButton addTarget:self action:@selector(dodownVoice:) forControlEvents:UIControlEventTouchDown];
    [recordingButton addTarget:self action:@selector(doDragUp:) forControlEvents:UIControlEventTouchDragExit];
    [self addSubview:recordingButton];
//    [recordingButton release];
    
    
    self.timeLabel=[[UILabel alloc] initWithFrame:CGRectMake((kScreenWidth-100)/2, 10, 100, 20)];
    self.timeLabel.text=@"按住说话";
    self.timeLabel.textAlignment=NSTextAlignmentCenter;
    self.timeLabel.textColor=[UIColor lightGrayColor];
    [self addSubview:self.timeLabel];
    timeCount=0;
    [self readyaudio];
}
//录音设置
- (void)readyaudio
{
//    AVAudioSession * audioSession = [AVAudioSession sharedInstance];
//    [audioSession setActive:YES error:nil];
    
    //录音设置
    NSMutableDictionary *recordSetting = [[NSMutableDictionary alloc]init];
    //设置录音格式  AVFormatIDKey==kAudioFormatLinearPCM
    [recordSetting setValue:[NSNumber numberWithInt:kAudioFormatMPEG4AAC] forKey:AVFormatIDKey];
    //设置录音采样率(Hz) 如：AVSampleRateKey==9980/44100/96000（影响音频的质量）
    [recordSetting setValue:[NSNumber numberWithFloat:44100] forKey:AVSampleRateKey];
    //录音通道数  1 或 2
    [recordSetting setValue:[NSNumber numberWithInt:1] forKey:AVNumberOfChannelsKey];
    //线性采样位数  8、16、24、32
    [recordSetting setValue:[NSNumber numberWithInt:16] forKey:AVLinearPCMBitDepthKey];
    //录音的质量
    [recordSetting setValue:[NSNumber numberWithInt:AVAudioQualityHigh] forKey:AVEncoderAudioQualityKey];
    
//    [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryAmbient error:nil];
    
    NSURL *url=[NSURL fileURLWithPath:[NSTemporaryDirectory() stringByAppendingPathComponent:[NSString stringWithFormat: @"%@.%@",@"voice",@"caf"]]];
    
    NSError *error;
    //初始化
    self.recorder = [[AVAudioRecorder alloc]initWithURL:url settings:recordSetting error:&error];
    //开启音量检测
    self.recorder.delegate=self;
    self.recorder.meteringEnabled = YES;
}

- (void)doupVoice:(UIButton *)sender{
}
//按下手指
- (void)dodownVoice:(UIButton *)btn
{
    recordingButton.selected=YES;
}
//手指移出取消发送
- (void)doDragUp:(id)sender
{
    recordingButton.selected=NO;
}
- (void)audioRecorderDidFinishRecording:(AVAudioRecorder *)recorder successfully:(BOOL)flag
{
     [[AVAudioSession sharedInstance] setActive:NO error:nil];
}
- (void)doLongPress:(UILongPressGestureRecognizer *)longpress
{
    
    if (longpress.state==UIGestureRecognizerStateBegan) {
        
        [[AVAudioSession sharedInstance] requestRecordPermission:^(BOOL granted) {
            if (granted) {
                // 用户同意获取数据
                
//                if ([[VideoManagerCenter instance] isOnlineChat]) {
//                    [self showCustomHudSingleLine:@"视频通话中无法录制语音"];
//                    return;
//                }
                
                
                recordingButton.selected=YES;
                point_begain=[longpress locationInView:[self superview]];
//                [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryRecord error:nil];
                if ([self.recorder prepareToRecord]) {
                    //开始
                    isRecoreding=YES;
                    [self.recorder record];
                    [self.recorder recordForDuration:60];
                }
                timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(detectionVoice) userInfo:nil repeats:YES];
            } else {
                // 可以显示一个提示框告诉用户这个app没有得到允许？
                [[[UIAlertView alloc] initWithTitle:@"麦克风被禁用" message:@"请在iPhone的“设置-隐私-麦克风”中允许安好访问您的麦克风。" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil] show];
                return;
            }
        }];

    }
    else if(longpress.state==UIGestureRecognizerStateEnded){
        
        double cTime = self.recorder.currentTime;
        if (cTime >= 1&&cTime<60) {//如果录制时间<1 不发送
            recordingButton.selected=NO;
            NSString *voicelength=[NSString stringWithFormat:@"%.f",cTime];
            [self.recorder stop];
            [timer invalidate];
//            [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategorySoloAmbient error:nil];
            //将音频文件转换成data
            NSData *voiceData=[NSData dataWithContentsOfURL:[NSURL fileURLWithPath:[NSTemporaryDirectory() stringByAppendingPathComponent:[NSString stringWithFormat: @"%@.%@",@"voice",@"caf"]]]];
            if (self.voiceDelegate&&[self.voiceDelegate respondsToSelector:@selector(sendVoice: withVoicelength:)]) {
                [self.voiceDelegate sendVoice:voiceData withVoicelength:voicelength];
            }
        }
        else {
            if ([self.recorder record]) {
                [self.recorder stop];
                [self.recorder deleteRecording];
            }
            //删除存储的
            [timer invalidate];
            if (isCancel) {
                isCancel=NO;
            }else
            {
//                self.imageView.hidden=NO;
//                [UIView animateWithDuration:2 animations:^{
//                    self.imageView.image=[UIImage imageNamed:@"shorttime.png"];
//                } completion:^(BOOL finished) {
//                    [self performSelector:@selector(doAnnikill) withObject:nil afterDelay:1];
//                }];
            }
        }
        timeCount=0;
        self.timeLabel.text=@"按住说话";
        recordingButton.selected=NO;
        
    }
    else if (longpress.state==UIGestureRecognizerStateChanged){
        recordingButton.selected=NO;
        
        isCancel=YES;
        if (isRecoreding) {
            CGPoint point=[longpress locationInView:[self superview]];
            if (point_begain.y-point.y>20) {
                //删除录制文件
                [self.recorder deleteRecording];
                [self.recorder stop];
                isRecoreding=NO;
//                [UIView animateWithDuration:1 animations:^{
//                    self.imageView.image=[UIImage imageNamed:@"voiceCancel.png"];
//                } completion:^(BOOL finished) {
//                    self.imageView.hidden=YES;
//                    [self performSelector:@selector(doAnnikill) withObject:nil afterDelay:0.5];
//                }];
                [timer invalidate];
                
            }
        }
    }

}
- (void)detectionVoice
{
    //录音时音量的动画
    timeCount++;
    [self.recorder updateMeters];//刷新音量数据
    //获取音量的平均值  [recorder averagePowerForChannel:0];
    //音量的最大值  [recorder peakPowerForChannel:0];
//    double lowPassResults = pow(10, (0.05 * [self.recorder peakPowerForChannel:0]));
    if (timeCount>=60) {
        [timer invalidate];
        timeCount=0;

    }else
    {
        if (timeCount<10) {
            self.timeLabel.text=[NSString stringWithFormat:@"00:0%ld",timeCount];
        }else{
            self.timeLabel.text=[NSString stringWithFormat:@"00:%ld",timeCount];
        }
    }
    //最大50  0
    //图片 小 --> 大
//    if (0<lowPassResults<=0.16) {
//        [self.imageView setImage:[UIImage imageNamed:@"record_animate_01.png"]];
//    }else if (0.16<lowPassResults<=0.32) {
//        [self.imageView setImage:[UIImage imageNamed:@"record_animate_02.png"]];
//    }else if (0.32<lowPassResults<=0.48) {
//        [self.imageView setImage:[UIImage imageNamed:@"record_animate_03.png"]];
//    }else if (0.48<lowPassResults<=0.64) {
//        [self.imageView setImage:[UIImage imageNamed:@"record_animate_04.png"]];
//    }else if (0.64<lowPassResults<=0.98) {
//        [self.imageView setImage:[UIImage imageNamed:@"record_animate_05.png"]];
//    }else{
//        [self.imageView setImage:[UIImage imageNamed:@"record_animate_06.png"]];
//    }
}
-(void)doAnnikill
{
    recordingButton.selected=NO;
}
- (void)dotapGes:(UITapGestureRecognizer *)tapges
{

//    self.imageView.image=nil;
//    [UIView animateWithDuration:1 animations:^{
//        self.imageView.image=[UIImage imageNamed:@"shorttime.png"];
//    } completion:^(BOOL finished) {
//        //self.imageView.hidden=YES;
//        [self performSelector:@selector(doAnnikill) withObject:nil afterDelay:0.5];
//    }];
}
-(void)showCustomHudSingleLine:(NSString *)text
{
    UIView *customHud = [[UIView alloc] init];
    customHud.tag = 888;
    
    int width = text.length * 16 + 40;
    int height = 60;
    customHud.frame = CGRectMake((kScreenWidth - width)/2, (kScreenHeight - height)/2, width, height);
    customHud.layer.masksToBounds = YES;
    customHud.layer.cornerRadius = 8;
    customHud.backgroundColor = [UIColor blackColor];
    customHud.alpha = 0;
    
    UILabel *contenLabel = [[UILabel alloc] initWithFrame:CGRectMake(20, 20, width - 40, height - 40)];
    contenLabel.text = text;
    contenLabel.textColor = [UIColor whiteColor];
    contenLabel.font = [UIFont boldSystemFontOfSize:16];
    contenLabel.numberOfLines = 0;
    contenLabel.textAlignment = NSTextAlignmentCenter;
    [customHud addSubview:contenLabel];
    
    [[[UIApplication sharedApplication].delegate window] addSubview:customHud];
    
    
    
    [UIView animateWithDuration:0.3f animations:^{
        customHud.alpha = 0.8;
    } completion:^(BOOL finished) {
        
        [UIView animateWithDuration:1.5f animations:^{
            customHud.alpha = 0;
        } completion:^(BOOL finished) {
            customHud.hidden = YES;
            [customHud removeFromSuperview];
        }];
        
    }];
    
    //    [self performSelector:@selector(hideCustomHud) withObject:nil afterDelay:1.0f];
}

/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/

@end
